#   Copyright 2006 Jerome Lacoste (jerome@coffeebreaks.org)
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
class ReportsController < ApplicationController

  before_filter :authorize, :except => [ :list ]

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list_reports
    # FIXME refactor with clients controller#list
    @owner = User.find(session[:user_id])
    @client_pages, @clients = pagination @owner.clients
  end

  # list all worklogs for a particular client...
  def list
    if request.get?
      time_period = TimePeriod.this_month()
      short = params[:id]
    else
      hash = params[:search_criteria]
      from = Time.local(hash['from_date(1i)'],hash['from_date(2i)'], hash['from_date(3i)'], hash['from_date(4i)'], hash['from_date(5i)'])
      to = Time.local(hash['to_date(1i)'],hash['to_date(2i)'], hash['to_date(3i)'], hash['to_date(4i)'], hash['to_date(5i)'])
      time_period = TimePeriod.new(from, to)
      short = params['client']['short']
    end

    # FIXME pagination 
    list_worklogs(short, time_period)
  end

  def show
    @worklog = Worklog.find(params[:id])
  end

  private
  # return a Hash of user_id -> users for the specified array of user_ids
  def find_workers_hash(user_ids)
    users = Hash.new
    if (user_ids.length > 0)
      # http://www.bigbold.com/snippets/posts/show/302
      aUsers = User.find( :all, :conditions => [ "id IN (?)", user_ids ] )
      users.update Hash[*aUsers.collect() { |u| [u.id, u] }.flatten]
    end
    users
  end

  def search_worklogs()
    @worklogs = Worklog.find_by_worklog_search_criteria(@search_criteria)

    # create a hash of user_id -> users for the users that worked in the above worklogs
    user_ids = @worklogs.collect() { |w| w.assignment.user_id }.uniq
    @users = find_workers_hash(user_ids)

    s = 0.0
    @worklogs.each() { |w| s += w.duration }
    @sum = s

    @sums = Hash.new
    # various stats...
    sums_for_users = @worklogs.each() { |w|
       id = 'user-' + w.assignment.user_id.to_s
       @sums[id] = w.duration + (@sums[id]? @sums[id] : 0)
    }
    # various stats...
    sums_for_users = @worklogs.each() { |w|
       id = 'project-' + w.assignment.project_id.to_s
       @sums[id] = w.duration + (@sums[id]? @sums[id] : 0)
    }
  end

  def list_worklogs(short, time_period)
    @client = find_client(short)
    return if @client.nil? 

    @projects = Project.find(:all)
    @search_criteria = WorklogSearchCriteria.new(time_period, @client.id)
    search_worklogs()
  end

  def find_client(short)
    if (short.nil? )
      redirect_to_index("Missing client name ")
      return nil
    end

    client = Client.find_by_short(short)

    if (client.nil?)    
      logger.error("Attempt to access invalid client #short}")
      redirect_to_index("Invalid client.")
      return nil
    end
    @client = client
  end  
end
